package com.ruleengine.worker.runner.rule.compute;

import static com.ruleengine.worker.runner.rule.RuleArgsField.COMPUTE_RULE_FILTER_KEY;

import com.api.jsonata4java.expressions.Expressions;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruleengine.util.JsonUtil;
import com.ruleengine.util.exception.JsonException;
import com.ruleengine.util.model.Message;
import com.ruleengine.worker.model.Rule;
import com.ruleengine.worker.runner.rule.PubSubRuleRunner;

import io.vertx.core.Vertx;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lianghanwei on 2024/3/20
 */
@Slf4j
public class JsonFilterRuleRunner extends PubSubRuleRunner<Message, Message> {
    private final String filterExpression;

    public JsonFilterRuleRunner(Vertx vertx, String name, Rule rule) {
        super(vertx, name, rule);
        this.filterExpression = rule.getSpec().getArgs().get(COMPUTE_RULE_FILTER_KEY);
    }

    @Override
    public Message process(Message item) {
        // TODO-lhw-2024/03/20: Valid json
        String jsonMsg = new String(item.getMessage());
        JsonNode jsonNode = JsonUtil.parseJsonNode(jsonMsg);
        String prettyJson = JsonUtil.toPrettyJson(jsonNode);

        try {
            Expressions expr = Expressions.parse(filterExpression);
            JsonNode result = expr.evaluate(jsonNode);

            // 根据这个表达式结果（boolean 结果）判断 item 消息是否需要过滤
            if (result == null || !result.isBoolean() || result.asBoolean() == true) {
                log.info("Match filter expression={}, will filter this json={}", filterExpression, prettyJson);
                return null;
            } else {
                log.info("Not match filter expression={}, will not filter this json={}", filterExpression, prettyJson);
                return item;
            }
        } catch (Exception e) {
            log.error("Process filterExpression failed", e);
            throw new JsonException("Process filterExpression failed", e);
        }
    }
}
